﻿#region " LICENSE "
// DRILL - Dependency Resolution Interface Layer Library
// Copyright (c) 2008-2012 Wade A. Reynolds. All rights reserved.
// http://drill.codeplex.com/
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Concurrent;
using System.Web.Mvc;
using System.Web.Routing;

namespace Drill.Integration.Web.Mvc
{
	/// <summary>
	/// A controller factory implementation that uses the specified dependency resolver 
	/// to obtain controller instances and falls back to a wrapped controller factory 
	/// if the dependency resolver fails to return a controller instance.
	/// </summary>
	public class DependencyResolverControllerFactory : DefaultControllerFactory
	{
		private readonly IControllerFactory _innerControllerFactory;
		private readonly IDependencyResolver _dependencyResolver;
		private static readonly ConcurrentDictionary<string, bool> _shouldResolveMap = new ConcurrentDictionary<string, bool>();

		/// <summary>
		/// Initializes a new instance of the <see cref="DependencyResolverControllerFactory" /> class.
		/// </summary>
		/// <param name="dependencyResolver">The dependency resolver.</param>
		/// <param name="innerControllerFactory">The inner controller factory.</param>
		/// <exception cref="System.ArgumentNullException">innerControllerFactory</exception>
		public DependencyResolverControllerFactory(IDependencyResolver dependencyResolver, IControllerFactory innerControllerFactory = null)
		{
			if (null == dependencyResolver)
			{
				throw new ArgumentNullException("dependencyResolver");
			}

			_dependencyResolver = dependencyResolver;
			_innerControllerFactory = innerControllerFactory;
		}

		public override IController CreateController(RequestContext requestContext, string controllerName)
		{
			return 
				GetControllerInstance(requestContext, controllerName)
					?? base.CreateController(requestContext, controllerName);
		}

		private IController GetControllerInstance(RequestContext requestContext, string controllerName)
		{
			// Attempt to obtain the controller instance from the dependency resolver 
			// only if the shouldResolve flag is true. If the controller cannot or should not 
			// be resolved by the dependency resolver, fall through to the inner controller factory 
			// if it is not null, otherwise fall back to the default behavior.

			// Attempt to lookup the shouldResolve value from the cache (the dictionary).
			// If it is not cached (not in the dictionary), invoke the delegate.
			bool isCached = (_shouldResolveMap.Count > 0) && _shouldResolveMap.ContainsKey(controllerName);
			bool shouldResolve = (false == isCached) || _shouldResolveMap[controllerName];

			IController controller = 
				shouldResolve
					? ResolveControllerInstance(controllerName)
					: null;

			if (null == controller)
			{
				// The controller could not be resolved by the dependency resolver.
				// Use the _innerControllerFactory to get the controller.
				// If the _innerControllerFactory is null, use the default base class behavior.
				// Explicitly set shouldResolve to false in order to ensure that the correct 
				// boolean value is cached in _shouldResolveMap to optimize future lookups 
				// by avoiding unnecessary calls to the dependency resolver.
				shouldResolve = false;
				if (null != _innerControllerFactory)
				{
					controller = _innerControllerFactory.CreateController(requestContext, controllerName);
				}
			}

			// If shouldresolve is not cached, cache it now.
			if (false == isCached)
			{
				_shouldResolveMap.TryAdd(controllerName, shouldResolve);
			}
			return controller;
		}

		private IController ResolveControllerInstance(string controllerName)
		{
			IController controller;
			try
			{
				controller = _dependencyResolver.GetInstance<IController>(controllerName);
			}
			catch
			{
				// The dependency resolution failed. This is most likely caused by a missing 
				// type and/or type mapping registration in the config file or registry objects  
				// used to initialize the underlying resolver. (e.g. Unity, StructureMap, etc.)
				// 
				// Ignore exceptions here so that fail resolution attempts 
				// will flow through to the base controller factory implementation.
				controller = null;
			}
			return controller;
		}
	}
}